﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TeamAble : MonoBehaviour 
{	
	public Renderer targetRenderer;
	[HideInInspector]public PhotonView photView;
	public Color friendlyColor;
	public Color enemyColor;
	public RightClickOption attackOption;
	public int team;
	[HideInInspector]public PhotonNetworkManager networkManager;
	/*
	0: team 0
	1: team 1
	2: can be attacked by anyone
	3: can be attacked by no one
	*/

	public bool isPlayer = true;

	void Start()
	{	
		networkManager = GameManager.instance.photonNetworkManager;
		photView = PhotonView.Get (this);
		StartCoroutine(DelayedStart());
	
	}
	IEnumerator DelayedStart()
	{
	yield return new WaitForSeconds(0.1F);
	if (photView.isMine && !photView.isSceneView)
		{
			team = networkManager.myTeam;
		}
		networkManager.SetAllColors ();

	}
		
		
	void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{
		if (stream.isWriting)
		{	
			stream.SendNext (team);
	}else if (stream.isReading)
	{	
		team = (int)stream.ReceiveNext ();
	}
	}

	public void SetColor()
	{	
		if (networkManager == null)
		{
			networkManager = GameManager.instance.photonNetworkManager;
		}
		if (team != networkManager.myTeam)
		{
			
			if (attackOption != null)
			{
				attackOption.enabled = true;
			}
			if (targetRenderer != null)
			{
				targetRenderer.material.color = enemyColor;
			}
		} else
		{
			if (!photView.isMine || photView.isSceneView)
			{	
				if (targetRenderer != null)
				{
					targetRenderer.material.color = friendlyColor;
				}
				if (attackOption != null)
				{
					attackOption.enabled = false;
				}
			}

		}	
	}
}
